package cn.woowc.through.loader;

import cn.woowc.through.listener.event.ThroughApplicationEvent;
import cn.woowc.through.listener.event.ThroughNatLogInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.ClassPathResource;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Objects;

/**
 * @version V1.0.0
 * @ClassName: {@link NatAppAfterInitLoader}
 * @Description: Socket 初始化后加载
 * @author: Lanzhou
 * @date: 2021/4/29 17:08
 * @Copyright:2020 All rights reserved.
 */
@Slf4j
@ConditionalOnProperty(name = {"through.adopt"}, havingValue = "nat")
public class NatAppAfterInitLoader extends RunBatInitLoader {

    @Value("${through.auth-token}")
    private String authToken;

    @Value("${through.show-addr}")
    private boolean showAddr;

    private static final String OK = "OK";

    @Resource
    private ApplicationContext context;

    /**
     * 环境资源
     */
    private static final String[] ENV_RESOURCE = {"cmd/natapp.exe"};

    @PostConstruct
    public void init() {
        try {
            createRunEnv(ENV_RESOURCE);
            String logPath = batBash();
            if (null != logPath && showAddr) {
                ThroughNatLogInfo info = new ThroughNatLogInfo(logPath);
                context.publishEvent(new ThroughApplicationEvent(info));
            }
        } catch (IOException e) {
            log.error("初始加载失败, 请检查参数配置", e);
        }
    }

    /**
     * 生并执行 Bat 文件
     *
     * @return
     * @throws IOException
     */
    private String batBash() throws IOException {
        // 把你的执行文件脚本路径写在这里
        ClassPathResource classPathResource = new ClassPathResource("cmd/natapp.exe");
        boolean exists = classPathResource.exists();
        if (exists) {
            File file = classPathResource.getFile();
            String path = file.getAbsolutePath();
            String name = file.getName();
            // 获取盘符
            String pathAddr = path.split(":")[0];
            // 进入所在的文件位置
            String pathInfo = path.replace(name, "");
            String order = pathAddr + "\n" +
                    "CD " + pathInfo + "\n" +
                    "cmd.exe /c start ./natapp -authtoken=" + authToken + " -log=./natapp.log -loglevel=INFO";
            String batPath = pathInfo + "natapp.bat";
            String logPath = pathInfo + "natapp.log";
            // 悄咪咪的搞个垃圾回收到总部去
            clearRubbish(Arrays.asList(batPath, logPath));
            // 穿件Bat运行时文件
            createRunBat(batPath, order);
            // 执行
            String status = execBat(batPath);
            if (Objects.equals(status, OK)) {
                return logPath;
            }
        }
        return null;
    }


    /**
     * 清除垃圾
     */
    private void clearRubbish(Collection<String> rubbish) {
        for (String path : rubbish) {
            File file = new File(path);
            if (file.exists()) {
                boolean delete = file.delete();
                log.debug("清除缓存文件 [ {} ] 执行, 状态: [ {} ]", path, delete);
            }
        }
    }

}
